package oj.hot100;

import java.util.Stack;

public class 字符串解码 {
    public String decodeString(String ss) {
        Stack<StringBuffer> st = new Stack<>();
        st.add(new StringBuffer());//添加一个空字符串,最后一步的逻辑才不会越界.
        Stack<Integer> sn = new Stack<>();
        char[] s = ss.toCharArray();
        int n = s.length,i = 0;
        while(i < n) {
            //处理数字
            if(s[i] >= '0' && s[i] <= '9') {
                int tmp = 0;
                while(i < n && s[i] >= '0' && s[i] <= '9') {
                    tmp = tmp*10 + (s[i]-'0');
                    i++;
                }
                sn.push(tmp);
            }else if(s[i] == '[') {
                //处理 [ 后跟的字符
                i++;
                // if(s[i] >= 'a' && s[i] <= 'z') {
                //就算是数字也要new
                StringBuffer str = new StringBuffer();
                while(i < n && s[i] >= 'a' && s[i] <= 'z') {
                    str.append(s[i]);
                    i++;
                }
                st.add(str);
                // }
            }else if(s[i] == ']') {
                //弹出两个栈的顶元素并解析,解析完成之后将其拼接到字符串栈顶元素当中.
                StringBuffer base = st.pop();
                int count = sn.pop();
                while(count-- > 0) {
                    st.peek().append(base);
                }
                i++;
            }else {
                //遇到单独字符,将其放到栈顶元素的后面
                StringBuffer str = new StringBuffer();
                while(i < n && s[i] >= 'a' && s[i] <= 'z') {
                    str.append(s[i]);
                    i++;
                }
                st.peek().append(str);
            }
        }
        return st.peek().toString();
    }
}
